package com.demo.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常类
 */
@ControllerAdvice(basePackages = "com.demo.controller")
public class GlobalExceptionHandler {

    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Map<String, Object> errorResult(Exception ex){
        //打印异常
        ex.printStackTrace();
        Map<String, Object> errorResultMap = new HashMap<String,Object>();
        BaseException baseException = null;
        if(ex instanceof BusinessException) {
            logger.error("业务异常："+ex.getMessage(), this.getClass());
            baseException = (BusinessException)ex;

        } else if(ex instanceof UncheckException) {
            logger.error("非检查异常："+ex.getMessage(), this.getClass());
            baseException = (UncheckException)ex;
        } else {
            logger.error("系统异常："+ex, this.getClass());
            baseException = new BaseException(-1,"系统异常："+ex.getMessage());
        }
        errorResultMap.put("errorCode",baseException.getErrorCode());
        errorResultMap.put("errorMsg",baseException.getMessage());
        return errorResultMap;
    }
}
